package com.weixinli.web.actions;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.apache.ibatis.builder.BaseBuilder;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.weixinli.beans.DetailInfo;
import com.weixinli.beans.Smile;
import com.weixinli.beans.UserComment;
import com.weixinli.beans.UserGood;
import com.weixinli.beans.UserInfo;
import com.weixinli.biz.IDetailInfoBiz;
import com.weixinli.biz.ISmileBiz;
import com.weixinli.biz.IUserCommentBiz;
import com.weixinli.biz.IUserGoodBiz;
import com.weixinli.utils.PageUtil;
import com.weixinli.utils.SessionAttributeName;
import com.weixinli.web.actions.model.JsonObject;

import Decoder.BASE64Decoder;

@Scope("prototype")
@Controller("smileAction")
public class SmileAction extends ActionSupport implements SessionAware{
	
	private static final long serialVersionUID = 1L;
	
	@Resource(name="iSmileBiz")
	private ISmileBiz smileBiz;
	@Resource(name="iUserGoodBiz")
	private IUserGoodBiz userGoodBiz;
	@Resource(name="iDetailInfoBiz")
	private IDetailInfoBiz detailInfoBiz;
	@Resource(name="iUserCommentBiz")
	private IUserCommentBiz userCommentBiz;
	@Resource(name="jsonObject")
	private JsonObject jsonObject;
	
	private Smile smile;
	private UserComment userComment;

	private File file; //要上传的表单元素的name属性值，这个名字必须和input上传文件标签里的name相同
	private String fileContentType;//上传文件的类型
	private String fileFileName; //上传文件的名称
	private String savePath;//用来接受依赖注入的文件保存路径

	private Map<String,Object> session;
	
	private String sid;
	
	private PageUtil pageUtil;
	
	private int page; //用来判断是点击下一页还是上一页
	
	private String imgData;
	
	/**
	 * 拍照上传
	 * @return
	 */
	public String photoUpload(){
		UserInfo uf=(UserInfo) session.get(SessionAttributeName.CURRENTUSER);
		
		Date date=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String time=sdf.format(date);
		smile.setStime(time);
		
		String fileName =System.currentTimeMillis() + ".png";
		String basePath = ServletActionContext.getServletContext().getRealPath("../WeiXinLiResouces");
		String filePath = basePath;
		String path="../WeiXinLiResouces/"+fileName;
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] bytes1;
		try {
			bytes1 = decoder.decodeBuffer(getImgData());
			ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
			BufferedImage image = ImageIO.read(bais);
			if (image != null){
				//保存图片到指定的目录和文件中
				ImageIO.write(image, "png", new File(filePath , fileName));
			}
		} catch (IOException e) {
			e.printStackTrace();
			return "error";
		}
		
		smile.setSaddr(path);
		smile.setW_uid(uf.getW_uid());
		
		int result=smileBiz.addSmile(smile);
		if( result>0 ){
			jsonObject.setResult(result);
			return "success";
		}else{
			return "error";
		}
		
	}
	
	/**
	 * 获取我的微笑的下一页
	 * @return
	 */
	public String pageMySmile(){
		PageUtil pageInfo=(PageUtil) session.get("smile_pageInfo");
		if( page == 1 ){  //上一页
			pageInfo.setPageNo( pageInfo.getPageNo()-1 );
		}else if( page == 2 ){ //下一页
			pageInfo.setPageNo( pageInfo.getPageNo()+1 );
		}else if( page ==3 ){ //首页
			pageInfo.setPageNo(1);
		}
		
		pageInfo.setPageSize(20); 
		
		UserInfo uf=(UserInfo) session.get(SessionAttributeName.CURRENTUSER);
		String gid="";
		if(uf==null || "".equals(uf) ){
			gid=userGoodBiz.findUserGood(null, 3);
		}else{
			gid=userGoodBiz.findUserGood(uf.getW_uid(), 3);
		}
		List<Smile> list=smileBiz.getMySmile(pageInfo.getPageNo(), pageInfo.getPageSize(),uf.getW_uid());
		int total=smileBiz.getTotalMySmile(uf.getW_uid());
		jsonObject.setRows(list);
		jsonObject.setTotal(total);
		
		Map<String,Object> map=new HashMap<String,Object>();
		
		map.put("pageNo", pageInfo.getPageNo());
		map.put("totalPage", pageInfo.getTotalPage());
		jsonObject.setObj(map);
		jsonObject.setGid(gid);
		
		return "success";
	}
	
	
	/**
	 * 点击smile.jsp的下一页
	 * @return
	 */
	public String pageSmile(){
		PageUtil pageInfo=(PageUtil) session.get("smile_pageInfo");
		if( page == 1 ){  //上一页
			pageInfo.setPageNo( pageInfo.getPageNo()-1 );
		}else if( page == 2 ){ //下一页
			pageInfo.setPageNo( pageInfo.getPageNo()+1 );
		}else if( page ==3 ){ //首页
			pageInfo.setPageNo(1);
		}
		
		pageInfo.setPageSize(20);
		
		UserInfo uf=(UserInfo) session.get(SessionAttributeName.CURRENTUSER);
		String gid="";
		if(uf==null || "".equals(uf) ){
			gid=userGoodBiz.findUserGood(null, 3);
		}else{
			gid=userGoodBiz.findUserGood(uf.getW_uid(), 3);
		}
		List<Smile> list=smileBiz.getPageSmile(pageInfo.getPageNo(), pageInfo.getPageSize());
		int total=smileBiz.getTotalSmile();
		jsonObject.setRows(list);
		jsonObject.setTotal(total);
		
		Map<String,Object> map=new HashMap<String,Object>();
		
		map.put("pageNo", pageInfo.getPageNo());
		map.put("totalPage", pageInfo.getTotalPage());
		jsonObject.setObj(map);
		jsonObject.setGid(gid);
		
		return "success";
	}
	
	/**
	 * 点击smile_index.jsp的下一页的评论信息
	 * @return
	 */
	public String pageComment(){
		PageUtil pageInfo=(PageUtil) session.get("smile_pageInfo");
		if( page == 1 ){  //上一页
			pageInfo.setPageNo( pageInfo.getPageNo()-1 );
		}else if( page == 2 ){ //下一页
			pageInfo.setPageNo( pageInfo.getPageNo()+1 );
		}
		List<UserComment> comment=userCommentBiz.getPageComment(pageInfo.getPageNo(), pageInfo.getPageSize(), Integer.valueOf(sid), 3);//查询被评论的对象的所有评论
		UserComment uc;
		DetailInfo df;
		for( int i=0;i<comment.size();i++ ){
			uc=comment.get(i);
			df=detailInfoBiz.getOneDeInfo(uc.getW_uid()); //查询评论人的uname
			uc.setTemp(df.getUname());
		}
		//获取被评论对象的总评论数
		int total=userCommentBiz.getTotalComment(Integer.valueOf(sid), 3);
		Map<String,Object> map=new HashMap<String,Object>();
		pageInfo.setTotalSize(total);;
		map.put("pageNo", pageInfo.getPageNo());
		map.put("totalPage", pageInfo.getTotalPage());
		jsonObject.setObject(map);
		jsonObject.setComment(comment); //存评论信息
		return "success";
	}
	
	/**
	 * 添加新的评论
	 * @return
	 */
	public String addComment(){
		UserInfo uf=(UserInfo) session.get(SessionAttributeName.CURRENTUSER); //获取当前用户
		userComment.setW_uid(uf.getW_uid());
		DetailInfo detailInfo=detailInfoBiz.getOneDeInfo(uf.getW_uid()); //查询登陆用户的头像存到数据库中
		userComment.setUserPhoto(detailInfo.getUpic());
		userCommentBiz.addUserComment(userComment); //存入数据库
		
		PageUtil pageInfo=(PageUtil) session.get("smile_pageInfo"); //获取分页信息
		pageInfo.setTotalSize(pageInfo.getTotalSize()+1);
		
		//查询最后一页的信息
		List<UserComment> list=userCommentBiz.getPageComment(pageInfo.getTotalPage(),pageInfo.getPageSize(), userComment.getObjid(), 3);//查询被评论的对象的所有评论
		UserComment uc;
		DetailInfo df;
		for( int i=0;i<list.size();i++ ){
			uc=list.get(i);
			df=detailInfoBiz.getOneDeInfo(uc.getW_uid()); //查询评论人的uname
			uc.setTemp(df.getUname());
		}
		jsonObject.setObj( pageInfo.getTotalPage() );
		jsonObject.setRows(list);
		return "success";
	}
	
	/**
	 * 获取微笑的详细信息
	 * @return
	 */
	public String detailSmile(){
		String sid=getSid(); //获取传过来的图片id
		session.put("sid", sid);
		List<Map<String,Object>> list=smileBiz.getOneSmile(sid);  //查询微笑的详细信息
		Smile smile=(Smile) list.get(0);
		DetailInfo detailInfo=detailInfoBiz.getOneDeInfo(smile.getW_uid());
		
		List<Smile> mySmile=smileBiz.getMySmile(1, 3, smile.getW_uid());
		
		List<UserComment> comment=userCommentBiz.getPageComment(1, 5, Integer.valueOf(sid), 3);//查询被评论的对象的所有评论
		UserComment uc;
		DetailInfo df;
		for( int i=0;i<comment.size();i++ ){
			uc=comment.get(i);
			df=detailInfoBiz.getOneDeInfo(uc.getW_uid()); //查询评论人的uname
			uc.setTemp(df.getUname());
		}
		//获取被评论对象的总评论数
		int total=userCommentBiz.getTotalComment(Integer.valueOf(sid), 3);
		Map<String,Object> map=new HashMap<String,Object>();
		pageUtil=new PageUtil();
		pageUtil.setTotalSize(total);;
		map.put("pageNo", pageUtil.getPageNo());
		map.put("totalPage", pageUtil.getTotalPage());
		session.put("smile_pageInfo", pageUtil);  //把页面的信息存到session中
		jsonObject.setObject(map);
		jsonObject.setComment(comment); //存评论信息
		jsonObject.setRows(list);  //存指定微笑的信息
		jsonObject.setObj(detailInfo);
		jsonObject.setInfo(mySmile);
		return "success";
	}
	
	/**
	 * 点赞
	 * @return
	 */
	public String addGood(){
		UserInfo uf=(UserInfo) session.get(SessionAttributeName.CURRENTUSER);
		String gid=userGoodBiz.findUserGood(uf.getW_uid(), 3);
		if(gid==null){
			userGoodBiz.addGood(uf.getW_uid(),sid,3);
		}else{
			if(gid.indexOf(",")>0){//判断是否有,号
				gid=gid+","+sid;
				String[] temp=gid.split(",");
				String str="";//中间一个字符串
				int count=0;//记数
				for(int i=0;i<temp.length;i++){
					if(temp[i].equals(sid)){
						count++;
					}
					str+=temp[i]+",";
				}
				if(count==2){//消除
					sid=str.replaceAll(sid+",","");
					sid=sid.substring(0, sid.lastIndexOf(","));
				}else if(count==1){//添加
					sid=str.substring(0, str.lastIndexOf(","));
				}
				userGoodBiz.updateGood(uf.getW_uid(), sid, 3);
			}else if(!sid.equals(gid)){//第二条数据添加
				sid=gid+","+sid;
				userGoodBiz.updateGood(uf.getW_uid(), sid,3); 
			}else{
				userGoodBiz.delUserGood(uf.getW_uid(), 3);
			}
		}
		return "success";
	}
	
	public String getSid() {
		return sid;
	}

	public void setSid(String sid) {
		this.sid = sid;
	}
	
	public void setUserGoodBiz(IUserGoodBiz userGoodBiz) {
		this.userGoodBiz = userGoodBiz;
	}
	
	/**
	 * 分页查询我的微笑信息
	 * @return
	 */
	public String mySmile(){
		UserInfo uf=(UserInfo) session.get(SessionAttributeName.CURRENTUSER);
		String gid=userGoodBiz.findUserGood(uf.getW_uid(), 3);
		List<Smile> list=smileBiz.getMySmile(smile.getMin(), smile.getMax(), smile.getW_uid());
		int total=smileBiz.getTotalMySmile(uf.getW_uid());
		jsonObject.setRows(list);
		jsonObject.setTotal(total);
		Map<String,Object> map=new HashMap<String,Object>();
		pageUtil=new PageUtil();
		pageUtil.setTotalSize(total);
		pageUtil.setPageSize(20);
		session.put("smile_pageInfo", pageUtil);
		map.put("pageNo", pageUtil.getPageNo());
		map.put("totalPage", pageUtil.getTotalPage());
		jsonObject.setObj(map);
		jsonObject.setGid(gid);
		return "success";
	}

	/**
	 * 分页查询微笑信息
	 * @return
	 */
	public String smileData(){
		UserInfo uf=(UserInfo) session.get(SessionAttributeName.CURRENTUSER);
		String gid="";
		if(uf==null || "".equals(uf) ){
			gid=userGoodBiz.findUserGood(null, 3);
		}else{
			gid=userGoodBiz.findUserGood(uf.getW_uid(), 3);
		}
		List<Smile> list=smileBiz.getPageSmile(smile.getMin(), smile.getMax());
		int total=smileBiz.getTotalSmile();
		jsonObject.setRows(list);
		jsonObject.setTotal(total);
		Map<String,Object> map=new HashMap<String,Object>();
		pageUtil=new PageUtil();
		pageUtil.setTotalSize(total);
		pageUtil.setPageSize(20);
		session.put("smile_pageInfo", pageUtil);
		map.put("pageNo", pageUtil.getPageNo());
		map.put("totalPage", pageUtil.getTotalPage());
		jsonObject.setObj(map);
		jsonObject.setGid(gid);
		return "success";
	}
	
	/**
	 * 添加新的微笑
	 * @return
	 */
	public String addSmile(){
		FileOutputStream fos=null;
		FileInputStream fis=null;
		
		try {
			fos=new FileOutputStream(getSavePath()+"\\"+getFileFileName());
			fis=new FileInputStream(file);
			
			byte[] buffer=new byte[1024];
			int len=0;
			
			while((len=fis.read(buffer))>0){
				fos.write(buffer,0,len);
			}
			fos.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return "error";
		} catch (IOException e) {
			e.printStackTrace();
			return "error";
		}finally{
			if(fos!=null){
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
					return "error";
				}
			}
			
			if(fis!=null){
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
					return "error";
				}
			}
		}
		smile.setSaddr(savePath+"/"+getFileFileName());
		int result=smileBiz.addSmile(smile);
		if( result>0 ){
			return "success";
		}else{
			return "error";
		}
		
	}

	public Smile getSmile() {
		return smile;
	}

	public void setSmile(Smile smile) {
		this.smile = smile;
	}

	public void setSmileBiz(ISmileBiz smileBiz) {
		this.smileBiz = smileBiz;
	}

	public void setSession(Map<String, Object> arg0) {
		this.session=arg0;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getSavePath() {
		return ServletActionContext.getServletContext().getRealPath(savePath);
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = new Date().getTime()+fileFileName;
	}

	public void setJsonObject(JsonObject jsonObject) {
		this.jsonObject = jsonObject;
	}

	public JsonObject getJsonObject() {
		return jsonObject;
	}

	public void setDetailInfoBiz(IDetailInfoBiz detailInfoBiz) {
		this.detailInfoBiz = detailInfoBiz;
	}

	public void setUserCommentBiz(IUserCommentBiz userCommentBiz) {
		this.userCommentBiz = userCommentBiz;
	}

	public UserComment getUserComment() {
		return userComment;
	}

	public void setUserComment(UserComment userComment) {
		this.userComment = userComment;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public PageUtil getPageUtil() {
		return pageUtil;
	}

	public void setPageUtil(PageUtil pageUtil) {
		this.pageUtil = pageUtil;
	}

	public String getImgData() {
		return imgData;
	}

	public void setImgData(String imgData) {
		this.imgData = imgData;
	}
	
}
